package org.lc.cmd.connect.impl.ws;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.lc.cmd.CmdSession;
import org.lc.cmd.connect.impl.BaseClientRequest;
import org.lc.cmd.connect.impl.util.JsonUtil;
import org.lc.cmd.model.CmdRequestData;
import org.lc.cmd.model.ConfirmData;
import org.lc.cmd.model.ConfirmResultData;
import org.lc.cmd.model.StyledString;
import org.lc.cmd.model.WsData;

import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;

@RequiredArgsConstructor
public class WsRequest extends BaseClientRequest {

    private final WsSession session;

    private final CmdRequestData data;

    @Setter
    private Function<ConfirmData, String> confirmHandler;

    private CompletableFuture<StyledString> completableFuture;

    @Override
    public CompletableFuture<StyledString> send() {
        WsData wsData = new WsData();
        wsData.setType("request");
        data.setRequestId(getId());
        wsData.setData(JsonUtil.toJson(data));
        session.sendData(wsData);
        CompletableFuture<StyledString> future = new CompletableFuture<>();
        completableFuture = future;
        return future;
    }

    @Override
    public CmdSession getSession() {
        return session;
    }

    public void handleFinish(StyledString result) {
        completableFuture.complete(result);
    }

    public void handleConfirm(ConfirmData data) {
        if (confirmHandler == null) {
            return;
        }
        String result = confirmHandler.apply(data);
        WsData wsData = new WsData();
        wsData.setType("request-confirm");
        ConfirmResultData resultData = new ConfirmResultData(getId(), data.getName());
        resultData.setResult(result);
        wsData.setData(JsonUtil.toJson(resultData));
        session.sendData(wsData);
    }

    public void handleClose() {
        StyledString str = new StyledString("服务端断开连接：" + ((WsSession) getSession()).getUrl() + "\n");
        completableFuture.complete(str);
    }
}
